package com.yungu.swift.api.route.v1.common;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yungu.swift.api.base.BaseApi;
import com.yungu.swift.api.utils.PayXmlUtils;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.constants.OrderConstant;
import com.yungu.swift.order.service.PayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Zerrion
 */

@RestController
@Api(value = "支付回调接口", tags = "支付回调接口")
public class TradeCallback extends BaseApi {
    private static Logger logger = LoggerFactory.getLogger(TradeCallback.class);

    @Reference
    private PayService payService;

    @RequestMapping(value = "/pay/wx/callback", method = {RequestMethod.POST, RequestMethod.GET})
    public String tenPayCallback(HttpServletRequest request) {
        ResponseData<String> responseData = payService.tradeCallback(OrderConstant.PAY_TYPE_TENPAY, PayXmlUtils.xmlToMap(request));
        if (responseData.isSuccess()) {
            return "<xml><return_code>SUCCESS</return_code></xml>";
        }
        logger.info(responseData.getMsg() + "--第三方回调失败，流程结束");
        return "<xml><return_code>FAIL</return_code></xml>";
    }

    @RequestMapping(value = "/pay/alipay/callback", method = {RequestMethod.POST, RequestMethod.GET})
    public String aliPayCallback(HttpServletRequest request) {
        ResponseData<String> responseData = payService.tradeCallback(OrderConstant.PAY_TYPE_ALIPAY,
                PayXmlUtils.build(OrderConstant.PAY_TYPE_ALIPAY, request));
        if (responseData.isSuccess()) {
            return "success";
        }
        logger.info(responseData.getMsg() + "--第三方回调失败，流程结束");
        return "fail";
    }

    @RequestMapping(value = "/api/v1/common/pay/callback", method = RequestMethod.POST)
    @ApiOperation(value = "主动执行支付回调", response = ResponseData.class)
    public ResponseData<String> invokeCallback(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid,
            @ApiParam(name = "orderUuid", value = "orderUuid", required = true) @RequestParam String orderUuid,
            HttpServletRequest request) {
        return payService.invokeCallback(orderUuid, getUserUid(request));
    }

}
